package com.mrli.cat.weather.service;

import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.mrli.cat.weather.activity.ForecastFragment;
import com.mrli.cat.weather.activity.WeatherPreferenceActivity;
import com.mrli.cat.weather.database.WeatherContract;
import com.mrli.cat.weather.model.City;
import com.mrli.cat.weather.tools.WriteCityAndUpdate;

/**
 * Created by MrLi on 2015/6/29.
 * 定位服务
 */
public class LocationService extends Service {
    public static final String TAG = LocationService.class.getName();
    private static LocationTask sLocationTask = null;
    private static final Object sLocationLock = new Object();

    @Override
    public void onCreate() {
        super.onCreate();
        synchronized (sLocationLock) {
            sLocationTask = new LocationTask(getApplicationContext());
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        sLocationTask.init();
        return 0;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return sLocationTask;
    }

    public class LocationTask extends Binder implements AMapLocationListener {

        private LocationManagerProxy mLocationManagerProxy;
        private Context mContext;

        public LocationTask(Context mContext) {
            this.mContext = mContext;
        }

        /**
         * 初始化定位
         */
        public void init() {
            mLocationManagerProxy = LocationManagerProxy.getInstance(mContext);
            mLocationManagerProxy.setGpsEnable(false);
            mLocationManagerProxy.requestLocationData(LocationProviderProxy.AMapNetwork, -1, 15, this);
            //开始定位消息
            LocalBroadcastManager manager = LocalBroadcastManager.getInstance(getApplicationContext());
            Intent startIntent = new Intent(ForecastFragment.ACTION_LOCATION_START);
            manager.sendBroadcast(startIntent);
        }

        /**
         * 停止定位
         */
        private void stopLocation() {
            if (mLocationManagerProxy != null) {
                mLocationManagerProxy.removeUpdates(this);
                mLocationManagerProxy.destroy();
            }
            mLocationManagerProxy = null;
        }


        @Override
        public void onLocationChanged(Location location) {

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }

        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            LocalBroadcastManager manager = LocalBroadcastManager.getInstance(getApplicationContext());
            //如果定位成功
            if (aMapLocation != null && aMapLocation.getAMapException().getErrorCode() == 0) {
                //停止定位
                stopLocation();
                String cityname = aMapLocation.getCity().substring(0, aMapLocation.getCity().length() - 1);
                City city = new City(cityname, aMapLocation.getLatitude(), aMapLocation.getLongitude());
                //向UI线程发送成功定位消息
                Intent intent = new Intent(ForecastFragment.ACTION_LOCATION_DONE);
                Bundle bundle = new Bundle();
                bundle.putParcelable(ForecastFragment.CITY_INFO, city);
                intent.putExtras(bundle);
                manager.sendBroadcast(intent);
                //第一次定位直接写入数据,并请求更新
                SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(ForecastFragment.INIT_SHAREDPREFERENCE, Context.MODE_PRIVATE);
                if (sharedPreferences.getBoolean(WeatherPreferenceActivity.INIT_KEY, true)) {
                    new WriteCityAndUpdate(getApplicationContext()).execute(city);
                }
            } else {
                Log.d("定位失败", "错误消息 " + aMapLocation.getAMapException().getErrorMessage());
                //如果定位失败, 向UI线程发送定位失败消息
                Intent intent = new Intent(ForecastFragment.ACTION_LOCATION_FALSE);
                manager.sendBroadcast(intent);
                //第一次写入默认位置
                City city = new City("郑州", 34.780814, 113.665765);
                SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(ForecastFragment.INIT_SHAREDPREFERENCE, Context.MODE_PRIVATE);
                if (sharedPreferences.getBoolean(WeatherPreferenceActivity.INIT_KEY, true)) {
                    new WriteCityAndUpdate(getApplicationContext()).execute(city);
                }
            }
        }
    }
}